import { computed, reactive, ref, watch } from "vue";
import useViewEditorStore from '@/store/viewEditor'

export default function useDrag(props: any) {
  const list = ref([])
  const showEmptyTip = computed(() => list.value.length === 0 && !props.dragging)
  const compUUID = ref(1000)
  
  const page = reactive({
    selected: false,
    data: {}
  })
  const viewEditorStore = useViewEditorStore()
  
  watch(() => viewEditorStore.PageConfig, (val) => {
    if (val) {
      Object.assign(page, JSON.parse(JSON.stringify(val)))
    }
  }, {
    immediate: true
  })

  watch(() => list.value, (val) => {
    if (!val || val.length === 0) {
      handleClickPage()
    }
  }, {
    immediate: true,
    deep: true
  })

  function handleClickPage() {
    clearAllSelected()
    page.selected = true
    viewEditorStore.updateSelectedElement(page)
  }

  function handleClickElement(element: any) {
    clearAllSelected()
    element.selected = true
    viewEditorStore.updateSelectedElement(element)
  }

  function handleDeleteElement(element: any, colElement: any = null) {
    if (element) {
      if (colElement) {
        const index = colElement.list.findIndex((col: any) => col.id === viewEditorStore.selectedElement.id)
        if (index > -1) {
          colElement.list.splice(index, 1)
          handleClickElement(element)
        }
      } else {
        const index = list.value.findIndex((item: any) => item.id === element.id)
        if (index > -1) {
          list.value.splice(index, 1)
          handleClickPage()
        }
      }
    }
  }

  function handleWidgetAdd({ newIndex }: any) {
    clearAllSelected();
    const ele = list.value[newIndex] as any
    ele.selected = true
    if (ele.data && ele.data.dataModel) {
      ele.data.dataModel.model = ele.data.dataModel.model || `key_${compUUID.value}`
      compUUID.value += 10
    }
    viewEditorStore.updateSelectedElement(ele)
  }

  function handleWidgetColAdd({ newIndex }: any, element: any) {
    clearAllSelected();
    const ele = element.list[newIndex] as any
    ele.selected = true
    if (ele.data && ele.data.dataModel) {
      ele.data.dataModel.model = ele.data.dataModel.model || `key_${compUUID.value}`
      compUUID.value += 10
    }
    viewEditorStore.updateSelectedElement(ele)
  }
  
  function clearAllSelected() {
    page.selected = false
    list.value.forEach((item: any) => {
      item.selected = false
      if (item.data && item.data.props && item.data.props.columns) {
        item.data.props.columns.forEach((col: any) => {
          if (col.list) {
            col.list.forEach((cell: any) => {
              cell.selected = false
            })
          }
        })
      }
    })
  }

  return {
    list,
    showEmptyTip,
    page,
    compUUID,
    handleWidgetAdd,
    handleClickElement,
    handleDeleteElement,
    handleClickPage,
    handleWidgetColAdd
  }

}